package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.*;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.ApiTypeEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.*;
import com.robert.vesta.util.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.xml.ws.Action;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class CashPocketService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CashPocketService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;


    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("cashpocket", this);
        BaseJobHandler.merchantAndServiceMap.put("plumpwallet", this);
    }


    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            return false;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/api/api/collection/collection-center-list/old?offset=0&limit=500";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(url, params, headers);
        if (StringUtils.isEmpty(result)) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return false;
        }

        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== CashPocketService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/api/api/collection/collection-center-list/old?offset=0&limit=500";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);


        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(url, params, headers);
        if (StringUtils.isEmpty(result)) {
            LOGGER.error("== 请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }

        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("item") == null) {
            LOGGER.info("== 请求接口数据为空 ==，account:{}", agentAccount.getAccount());
            return;
        }
        List<Any> items = resultJson.get("item").asList();
        if (CollectionUtils.isEmpty(items)) {
            LOGGER.info("== 请求接口数据为空  item 为空==，account:{}", agentAccount.getAccount());
            return;
        }

        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //如果为空则全部选择插入，这个其实就是初始化数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            LOGGER.info("==当天没有数活跃数据 开始插入新数据 ==，size:{}", items.size());
            items.forEach(item -> {
                try {
                    String collectionNo = IdUtils.genId() + "";
                    CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                            .setAgentCode(agentAccount.getAgentCode())
                            .setMerchantCode(agentAccount.getMerchantCode())
                            .setOrderNo(item.get("loanAppId").toString())
                            .setOrderInfo(item.toString())
                            .setStatus(OrderStatusEnum.active.getStatus())
                            .setCreateDt(new Date())
                            .setCollectionNo(collectionNo);
                    ordersDao.insert(ceOrdersEntity);
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
                }
            });
        } else {
            //更新数据
            LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());
            Map<String, CeOrdersEntity> activeOrdersMap = new HashMap<>();
            Set<String> newOrdersSet = new HashSet<>();
            activeOrders.forEach(o -> {
                activeOrdersMap.put(o.getOrderNo(), o);
            });
            items.forEach(item -> {
                String loanId = item.get("loanAppId").toString();
                newOrdersSet.add(loanId);
            });

            //如果更新之后发现有新的订单了，则继续插入
            items.forEach(item -> {
                try {
                    String loanId = item.get("loanAppId").toString();
                    if (!activeOrdersMap.containsKey(loanId)) {
                        LOGGER.info("==更新的时候发现有新的订单==,account:{},loanId:{}", agentAccount.getAccount(), loanId);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(item.get("loanAppId").toString())
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    }

                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
                }
            });

            //如果跟新之后发现数据比原来的少了，则需要更新订单状态
            activeOrdersMap.keySet().forEach(activeOrderNo -> {
                try {
                    if (!newOrdersSet.contains(activeOrderNo)) {
                        LOGGER.info("== 更新的时候发现有订单消失 目前认为是订单状态发生了改变 ==,account:{},loanId:{}", agentAccount.getAccount(), activeOrderNo);
                        CeOrdersEntity ceOrdersEntity = activeOrdersMap.get(activeOrderNo);
                        if (ceOrdersEntity.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            ceOrdersEntity.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(ceOrdersEntity);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.info("==更新的时候发现有订单 异常==,account:{},loanId:{}", agentAccount.getAccount(), activeOrderNo, e);
                }
            });
        }

        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;

                Map<String, String> infoMap = new HashMap<>();
                String orderInfo = order.getOrderInfo();
                String contractNo = JsonIterator.deserialize(orderInfo).get("contractNo").toString();
                String loanAppInfoUrl = merchant.getApiDomain() + "/api/api/review/loanAppInfo?contractNo=" + contractNo;
                String loanAppInfo = HttpUtil.getPage(loanAppInfoUrl, params, headers);
                infoMap.put("loanAppInfo", loanAppInfo);
                LOGGER.info("== 获取成功 loanAppInfo==");

                String collectionLoanDetailUrl = merchant.getApiDomain() + "/api/api/collection/collection-loan-detail?contractNo=" + contractNo;
                String collectionLoanDetail = HttpUtil.getPage(collectionLoanDetailUrl, params, headers);
                LOGGER.info("== 获取成功 collectionLoanDetail==");
                infoMap.put("collectionLoanDetail", collectionLoanDetail);

                if (!hasDetailData) {

                    String personalInfoUrl = merchant.getApiDomain() + "/api/api/review/personalInfo?contractNo=" + contractNo;
                    String personalInfo = HttpUtil.getPage(personalInfoUrl, params, headers);
                    infoMap.put("personalInfo", personalInfo);
                    LOGGER.info("== 获取成功 personalInfo==");

                    String emergencyContactInfoUrl = merchant.getApiDomain() + "/api/api/review/contact?contractNo=" + contractNo;
                    String emergencyContactInfo = HttpUtil.getPage(emergencyContactInfoUrl, params, headers);
                    LOGGER.info("== 获取成功 emergencyContactInfo==");
                    infoMap.put("emergencyContactInfo", emergencyContactInfo);

                    String addressBookUrl = merchant.getApiDomain() + "/api/api/review/all-income-message?contractNo=" + contractNo + "&protocolName=CONTACT";
                    String addressBook = HttpUtil.getPage(addressBookUrl, params, headers);
                    List<Any> contactList = new ArrayList<>();
                    try {
                        contactList = JsonIterator.deserialize(addressBook).get("data").asList();
                        if (CollectionUtils.isNotEmpty(contactList)) {
                            JSONArray contacts = new JSONArray();
                            for (Any vo : contactList) {
                                JSONObject j1 = new JSONObject();
                                j1.put("name", vo.get("name").toString());
                                List<Any> number = vo.get("number").asList();
                                if (CollectionUtils.isEmpty(number)) {
                                    j1.put("phone", "no-number");
                                } else {
                                    j1.put("phone", number.get(0).get("number").toString());
                                }
                                contacts.add(j1);
                            }
                            JSONObject jsonData = new JSONObject();
                            jsonData.put("contacts", contacts);

                            String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                            infoMap.put("contactUrl", contactUrl);
                        }
                    } catch (Exception e) {
                        LOGGER.error("== 通讯录转换错误 ==", e);
                    }

                    LOGGER.info("== 获取成功 contactInfo==");
                    String fileListUrl = merchant.getApiDomain() + "/api/api/review/fileList?contractNo=" + contractNo;
                    String fileList = HttpUtil.getPage(fileListUrl, params, headers);
                    LOGGER.info("== 获取成功 fileList==");
                    infoMap.put("fileList", fileList);

                    String workUrl = merchant.getApiDomain() + "/api/api/review/employment?contractNo=" + contractNo;
                    String workInfo = HttpUtil.getPage(workUrl, params, headers);
                    LOGGER.info("== 获取成功 workInfo==");
                    infoMap.put("workInfo", workInfo);

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("appName").toString();
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "")
                        .setClientCode(order.getMerchantCode())
                        .setAccount(order.getAgentCode());

                CeOrdersDetailEntity loanAppInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "loanAppInfo", order.getOrderNo());
                Any loanAppInfoJson = JsonIterator.deserialize(loanAppInfo.getDetailInfo());
                CeOrdersDetailEntity collectionLoanDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "collectionLoanDetail", order.getOrderNo());
                Any collectionLoanDetailJson = JsonIterator.deserialize(collectionLoanDetail.getDetailInfo());
                String borrowCapital = collectionLoanDetailJson.get("principalAccr").toString();
                String overdueDays = collectionLoanDetailJson.get("overdueDays").toString();
                String lateFee = collectionLoanDetailJson.get("defaultAccr").toString();
                if (lateFee.equals("0E-8")) {
                    lateFee = "0";
                }
                String overdueRatio = "0";
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }

                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                String paidAmount = collectionLoanDetailJson.get("receivedAmount").toString();
                if ("0E-8".equals(paidAmount)) {
                    paidAmount = "0";
                }
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(1)
                        .setBorrowCapital(loanAppInfoJson.get("amount").toString())
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest("0")
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(loanAppInfoJson.get("serviceFee").toString())
                        .setLateServiceFee("0")
                        .setReceivedCapital(new BigDecimal(borrowCapital).subtract(new BigDecimal(loanAppInfoJson.get("serviceFee").toString())).toString())
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(collectionLoanDetailJson.get("issueDate").toString())
                        .setRepaymentDate(collectionLoanDetailJson.get("dueDate").toString());

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "personalInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());

                String aadhaarNo = personalInfoJson.get("credentialNo").toString();
                String pancardNo = personalInfoJson.get("panCode").toString();
                String email = personalInfoJson.get("email").toString();

                CeOrdersDetailEntity workInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "workInfo", order.getOrderNo());
                Any workInfoJson = JsonIterator.deserialize(workInfo.getDetailInfo());
                String companyCity = workInfoJson.get("companyCity").toString();
                String companyProvince = workInfoJson.get("companyProvince").toString();

                CeOrdersDetailEntity emergencyContactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "emergencyContactInfo", order.getOrderNo());
                Any emergencyContactInfoJson = JsonIterator.deserialize(emergencyContactInfo.getDetailInfo());


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());

                String friendName = "no";
                String friendMobile = "no";

                String parentName = "no";
                String parentPhone = "no";

                List<Any> anies = emergencyContactInfoJson.asList();
                for (Any item : anies) {
                    String relationType = item.get("relation").get("key").toString().toLowerCase();
                    if ("parent".equals(relationType)) {
                        parentName = item.get("name").toString();
                        parentPhone = item.get("mobile").toString();
                    } else {
                        friendName = item.get("name").toString();
                        friendMobile = item.get("mobile").toString();
                    }
                }

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(companyProvince + " " + companyCity + " " + workInfoJson.get("companyAddress").toString())
                        .setBirthday(getBirthDayByAge(workInfoJson.get("age").toInt()))
                        .setCity(companyCity)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(0)
                        .setKycNo(aadhaarNo)
                        .setMobile(personalInfoJson.get("mobile").toString())

                        .setMarriedStatus(0)
                        .setName(personalInfoJson.get("fullName").toString())
                        .setPinCode("no")
                        .setState(companyProvince)

                        .setSex("female".equals(personalInfoJson.get("gender").toString()) ? 0 : 1)
                        .setContactUrl(contactUrlEntity.getDetailInfo());

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();
        waitingPaidCheckOrders.forEach(order -> {

            String orderInfo = order.getOrderInfo();
            String contractNo = JsonIterator.deserialize(orderInfo).get("contractNo").toString();
            String collectionLoanDetailUrl = merchant.getApiDomain() + "/api/api/collection/collection-loan-detail?contractNo=" + contractNo;
            String collectionLoanDetail = HttpUtil.getPage(collectionLoanDetailUrl, params, headers);
            Any loanAppInfoJson = JsonIterator.deserialize(collectionLoanDetail);

            CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "collectionLoanDetail", order.getOrderNo());
            byKeyAndMerchantAndOrderNo.setDetailInfo(collectionLoanDetail);
            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);

            if ("PAID_OFF".equals(loanAppInfoJson.get("loanAppStatus").get("key").toString())) {
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } else {
                order.setStatus(OrderStatusEnum.removed.getStatus());
                order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                String paidAmount = JsonIterator.deserialize(order.getOrderInfo()).get("dueAmount").toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                String paidAmount = JsonIterator.deserialize(order.getOrderInfo()).get("dueAmount").toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });
//

    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        try {
            Map headers = getHeaders(account);
            Map<String, String> params = Maps.newHashMap();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            params.put("comment", ceCommentPushLogEntity.getTargetMsg());
            params.put("type", "COLLECT");
            params.put("loanAppId", ceCommentPushLogEntity.getOriginNo());
            params.put("remindTime", DateUtil.getDate(ceCommentPushLogEntity.getGmtCreate(), "yyyy-MM-dd HH:mm"));
            params.put("category", "在whatsapp无法联系上（WP-LC）");

            String result = HttpUtil.postPage(ceMerchantEntity.getApiDomain() + "/api/api/collection/comments", params, headers);
            LOGGER.info("== 开始同步催记到甲方 ==,res:{}", result);

            if ("1".equals(result)) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==");
            }

        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo,boolean isReduce) {

        return "";
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        return "";
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }

    @Override
    public String queryPaymentOrderResult(String orderNo,String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        return null;
    }

    public static void main(String[] args) {
//        String aa = "[添加催收日志]:[在whatsapp无法联系上（WP-LC）][no response11],提醒时间[2022-01-07 17:39],贷款[110258]";
//        try {
//            String result = java.net.URLEncoder.encode(aa);
//            System.err.println("https://adminweb.cashpocket8.com/api/api/operation/save?content="+result+"&type=COLLECT");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//        Map headers = Maps.newHashMap();
//        headers.put("Content-Type", "application/x-www-form-urlencoded");
//        headers.put("X-ADMIN-TOKEN", "eyJsb2NhbGUiOiJlbl9VUyIsImFsZyI6IkhTNTEyIn0.eyJzdWIiOiJTMTAwNk1aIiwiZXhwIjoxNjQ0MDQ1ODk2fQ.KaTODF2hK7QaSBVRub_KopqIGNWuuJ0obOvVF1zdCPSY1j46bWKz76C0o2zkqd2yW9EiuleUyj6gWWgPvszBOA");
//        Map<String, String> params = Maps.newHashMap();
//        params.put("comment", "switch off11");
//        params.put("type", "COLLECT");
//        params.put("loanAppId", "110258");
//        params.put("remindTime", "2022-01-07 17:55");
//        params.put("category", "在whatsapp无法联系上（WP-LC）");
//
//        String result = HttpUtil.postPage("https://adminweb.cashpocket8.com/api/api/collection/comments", params, headers);

        String s = new BigDecimal("1048.00000000").divide(new BigDecimal("6"), 0, BigDecimal.ROUND_HALF_UP).toString();
        String s1 = new BigDecimal("1048.00000000").divide(new BigDecimal("6"), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal("4000.00000000"), 4, BigDecimal.ROUND_HALF_UP).toString();
        ;
        System.err.println(s);
        System.err.println(s1);
    }

    private static String getBirthDayByAge(Integer age) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        c.setTime(new Date());
        c.add(Calendar.YEAR, -age);
        Date y = c.getTime();
        return format.format(y);
    }
}
